//
//  WmcHomeVC+BindViewModel.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/7/21.
//

import UIKit
import YPGraphicEngine

extension WmcHomeVC {
    /// 模型事件
    func viewModelBind() {
        // 数据库迁移完成的回调
        WmcLocalMediaAlbumDBManager.setMigrationCompleteBlock { [weak self] in
            YPGCD.Delay(delay: 1) { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.viewModel.loadData() // 同步下数据
            }
        }
        
        // 监听网络状态
        YPNetworkReachability.monitoring().subscribe(onNext: { [weak self] type in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.getLastUseWatermark()
            weakSelf.checkNetworkStatus(type: type)
            weakSelf.updateSyncStatus()
            weakSelf.viewModel.queryLastSelectedRecognitionType { [weak self] model in
                guard let weakSelf = self else { return }
                weakSelf.controlView.aiLogoView.updateModel(model)
            }
        }).disposed(by: rx.disposeBag)
        
        // 上传任务完成需要显示小红点
        WmcUploadQueueManager.shared.completionSubject.subscribe(onNext: { [weak self] model in
            guard let weakSelf = self else { return }
            weakSelf.footerView.cloudAlbumBtn.setRedPointDisplay(true)
        }).disposed(by: rx.disposeBag)

        WmcTaskSchedulerManager.registerTask(key: .forbidEditDateTip) {
            var result: Bool = false
            if let isShowed: Bool = WmcUserdefault.object(forKey: .Tips.Home.banChangeTimeTipView) {
                result = isShowed
            }
            return !result
        } exceuteClosure: { [weak self] continueFunc in
            guard let weakSelf = self else { return }
            weakSelf.modifyTimeTipView.isHidden = false
            weakSelf.modifyTimeTipView.dismissClosure = {
                continueFunc()
            }
            WmcUserdefault.save(value: true, forKey: .Tips.Home.banChangeTimeTipView)
        }

        // 应用回到后台
        WmcAppStateManager.shared.appEnterBackground.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            // 取消延迟拍照
            weakSelf.cancelDelayTakePhoto()
            // 如果正在录视频，则停止保存
            switch weakSelf.viewModel.videoRecordState {
            case .being,
                 .pause: // 暂停和进行中时
                weakSelf.stopRecording(breakOffType: .appEnterBackground)
            default: break
            }
            // 时间提示视图
            if weakSelf.modifyTimeTipView.isHidden == false {
                weakSelf.modifyTimeTipView.dismiss()
            }
        }).disposed(by: rx.disposeBag)

        // 应用回到前台
        WmcAppStateManager.shared.becomeActive.subscribe(onNext: { [weak self] in
            guard let weakSelf = self else { return }
            // 更新水印
            weakSelf.updateWatermarkView()
            // 开启相机
            weakSelf.startCamera()
            // 闪光灯状态
            weakSelf.restoreFlashMode()
            // 刷新相册小红点
            weakSelf.updateCloudAlbumRedPoint()
        }).disposed(by: rx.disposeBag)

        // 电话状态监听
        WmcAppStateManager.shared.phoneCallState.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            // 取消延迟拍照
            weakSelf.cancelDelayTakePhoto()
            // 如果正在录视频，则停止保存
            switch weakSelf.viewModel.videoRecordState {
            case .being,
                 .pause: // 暂停和进行中时
                weakSelf.stopRecording(breakOffType: .phoneCall)
            default: break
            }
        }).disposed(by: rx.disposeBag)
        // 时间更新监听
        WmcDateManager.shared.networkDate.subscribe(onNext: { [weak self] value in
            YPGCD.Main { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.updateVideoWatermarkScreenshot() // 更新水印截图
            }
        }).disposed(by: rx.disposeBag)

        // 水印切换
        viewModel.watermarkRelay.subscribe(onNext: { [weak self] wmModel in
            guard let weakSelf = self else { return }
            // 询问外部代理
            var wmModel = wmModel
            if let changeModel = weakSelf.homeDelegate?.watermarkWillDraw(.current, watermarkModel: wmModel) {
                wmModel = changeModel
            }
            // 是否需要认证水印
            let showCertification = !WmcPreferenceSettingsManager.shared.cameraSetting.hiddenOfficialMark
            weakSelf.watermarkContentView.setWatermarkModel(wmModel, showCertification: showCertification)
        }).disposed(by: rx.disposeBag)

        // 本地数据库更新
        viewModel.localMediaAlbumPhotoListRelay.skip(1).subscribe(onNext: { [weak self] list in
             guard let weakSelf = self else { return }
             DispatchQueue.main.async { [weak self] in
                 guard let weakSelf = self else { return }
                 // 左下角预览按钮的图片替换
                 weakSelf.setPreViewImage()
                 weakSelf.footerView.localAlbumBtn.isEnabled = true
             }
         }).disposed(by: rx.disposeBag)

        // 图片处理完成
        viewModel.photoDisposeFinishRelay.subscribe(onNext: { [weak self] result in
            guard let self = self else { return } // 跳转逻辑
            switch self.viewModel.functionMode {
            case .photo:
                self.takePhotoToPreview(result)
            case .photoAndCombine: // 边拍边拼
                // 记录水印信息
                self.viewModel.lastWatermarkModel = result.watermarkModel
                //
                self.didGotDisposedCombined(photo: result.watermarkPhoto)
            default:
                break
            }
        }).disposed(by: rx.disposeBag)

        // 绑定相关业务
        bindViewModelBusiness()

        // 重载水印
        // 是否需要认证水印
        let showCertification = !WmcPreferenceSettingsManager.shared.cameraSetting.hiddenOfficialMark
        watermarkContentView.reloadWatermark(showCertification: showCertification)

        // 视频录制时，进度的回调
        viewModel.videoRecordingProgressRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.footerView.videoActionBtn.setProgress(value)
        }).disposed(by: rx.disposeBag)

        // 视频已录制时间
        viewModel.videoRecordingTimeRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.videoRecordingLabel.text = value
        }).disposed(by: rx.disposeBag)

        // 50s时提示弹窗
        viewModel.videoRecordingTipsTostRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.showVideoRecording50STips()
        }).disposed(by: rx.disposeBag)

        // 视频需要停止
        viewModel.videoStopRecordingRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.stopRecording(breakOffType: .timeOut)
        }).disposed(by: rx.disposeBag)

        // 定位权限变化的订阅
        WmcLocationManager.shared.locationAuthorizationPublish.subscribe(onNext: { [weak self] isAuthorized in
            guard let weakSelf = self else { return }
            if isAuthorized {
                weakSelf.positioningBtn.label.text = "重新定位"
//                weakSelf.locationTipView.dismiss()
                
                // TODO: zhouss 权限状态变化的监听需要优化，这里的逻辑有点蛋疼，APP启动后开始定位了，然后才返回了已授权的状态，强行把我的定位中的状态给重置了，这不扯犊子了么
                if WmcLocationManager.shared.locationStatus.value?.status != .fetching {
                    weakSelf.positioningBtn.label.text = "重新定位"
                }
                WmcTaskSchedulerManager.removeTask(key: .locationUnauthorizedTip)
            } else {
                WmcTaskSchedulerManager.registerTask(key: .locationUnauthorizedTip) {
                    return true
                } exceuteClosure: { [weak self] continueFunc in
                    guard let weakSelf = self else { return }
//                    weakSelf.showLocationTip()
//                    weakSelf.locationTipView.dismissClosure = {
//                        continueFunc()
//                    }
                }
                weakSelf.positioningBtn.label.text = "定位失败"
            }
        }).disposed(by: rx.disposeBag)

        // 定位状态刷新订阅
        WmcLocationManager.shared.locationStatus.subscribe(onNext: { [weak self] r in
            guard let weakSelf = self else { return }
            if r?.status == .failure {
                weakSelf.setLocationFailure()
                
                if !WmcAuthorizedManager.location().info.isAvailable {
//                    weakSelf.showLocationTip()
                }
            } else if r?.status == .fetching {
                weakSelf.setLocationWaiting()
            }
        }).disposed(by: rx.disposeBag)

        // poi数据刷新订阅
        WmcLocationManager.shared.poiStatus.subscribe(onNext: { [weak self] r in
            guard let weakSelf = self else { return }
            if r?.status == .updatePoiCompletion {
//                weakSelf.locationTipView.dismiss()
                weakSelf.setLocationSuccess()
            } else if r?.status == .updatePoiFailure {
//                if weakSelf.locationTipView.isHidden == false {
//                    return
//                }

                weakSelf.setLocationFailure()
            }
        }).disposed(by: rx.disposeBag)

        // 弹出更多权益弹窗
        viewModel.moreRightsRelay.subscribe(onNext: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.showLoginMoreRightsAlert {
                YPWmcManager.shared.delegate.loginDelegate?.loginNeed(.current, animated: true, success: {
                    WmcNavigatorManager.push(.myTeam)
                }, failure: {
                    WmcHudManager.toast("登录失败")
                })
            }
        }).disposed(by: rx.disposeBag)

        // 视频录制完成
        viewModel.finishedRecordingVideo.subscribe(onNext: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.showLoginMoreRightsAlert {
                YPWmcManager.shared.delegate.loginDelegate?.loginNeed(.current, animated: true, success: {
                    WmcNavigatorManager.push(.myTeam)
                }, failure: {
                    WmcHudManager.toast("登录失败")
                })
            }
        }).disposed(by: rx.disposeBag)

        // 右下角定位提示消失
        viewModel.locationTipsDismiss.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
//            weakSelf.locationTipView.dismiss()
        }).disposed(by: rx.disposeBag)

        // 右下角定位提示未授权
        viewModel.locationTipsUnauthorized.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            let locationStatus = WmcAuthorizedManager.location()
            WmcTrack.addEvent(id: "location_authorization", params: ["custom_status": locationStatus])

            WmcTaskSchedulerManager.registerTask(key: .locationUnauthorizedTip) {
                return !locationStatus.info.isAvailable
            } exceuteClosure: { [weak self] continueFunc in
                guard let weakSelf = self else { return }
                let locationStatus = WmcAuthorizedManager.location()
                if !locationStatus.info.isAvailable {
//                    weakSelf.showLocationTip()
//                    weakSelf.locationTipView.dismissClosure = {
//                        continueFunc()
//                    }
                }
            }
        }).disposed(by: rx.disposeBag)
        
        // 添加相机视图
        viewModel.addCameraViewRelay.subscribe (onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            // 相机授权后,隐藏提示
            weakSelf.cameraPermissonTipView.isHidden = true
            weakSelf.addCameraView()
        }).disposed(by: rx.disposeBag)
        
        // 启动时查询到定位无权限
        viewModel.locationNotAuthorized = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.setLocationFailure()
        }
        
        
        // 注册极光魔链通知
        let registerBlock: () -> Void = { [weak self] in
            guard let weakSelf = self else { return }
            WmcNotice.Register(WmcJMLinkActionProtocol.self, observer: weakSelf)
        }
        
        registerBlock()
        
        YPWmcManager.shared.loginSuccess.subscribe(onNext: { [weak self] in
            guard let weakSelf = self else { return }
            // 加载偏好设置
            weakSelf.footerView.updateCloudAlbumBtnStatus()
            // 注册同步照片
            weakSelf.viewModel.registerPhotoSynchronization()
            // 更新同步状态
            weakSelf.updateSyncStatus()
            // 更新小红点
            weakSelf.updateCloudAlbumRedPoint()
            // 更新云相册按钮状态
            weakSelf.footerView.updateCloudAlbumBtnStatus()
        }).disposed(by: rx.disposeBag)
    }
    
//    private func showLocationTip() {
//        if hasLocationTipShown {
//            return
//        }
//        locationTipView.isHidden = false
//        hasLocationTipShown = true
//    }
}
